package com.taraslaba.polvisachecker.server;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class CheckVisaUtil {
	private static final Logger logger = Logger.getLogger(CheckVisaUtil.class.getName());	
	
	private static final String VISA_SCHEDULE_INFO_URL = "https://www.visaservices.firm.in/poland-ukraine-appointment/AppScheduling/AppSchedulingGetInfo.aspx?p=s2x6znRcBRv7WQQK7h4MTjZiPRbOsXKqJzddYBh3qCA%3d";
	private static final String VISA_SCHEDULE_INFO_REFERER_URL = "https://www.visaservices.firm.in/poland-ukraine-appointment/AppScheduling/AppScheduling.aspx?p=s2x6znRcBRv7WQQK7h4MTjZiPRbOsXKqJzddYBh3qCA%3d";
	private static final String PATTERN = ".*<span id=\"ctl00_plhMain_lblMsg\" class=\"Validation\">(.*)</span>.*";
	//private static final String VISA_SCHEDULE_INFO_URL = "http://localhost/AuthDemo/VisaScheduleInfo.aspx";
	
	public static String getVisaShceduleInfo() throws MalformedURLException{
		URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
		HTTPRequest request = new HTTPRequest(new URL(VISA_SCHEDULE_INFO_URL), HTTPMethod.POST, FetchOptions.Builder.doNotValidateCertificate().doNotFollowRedirects());
		request.setHeader(new HTTPHeader("Referer", VISA_SCHEDULE_INFO_REFERER_URL));
		request.setHeader(new HTTPHeader("Accept-Charset", "utf-8"));
		String postData = "__EVENTTARGET=ctl00%24plhMain%24cboVisaCategory&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=7J4YuUcJ33QTzNSOWXPjb839rowT3BBU1Qm93BT3l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2FwxZhKWGXlkCrlUiCcQg5sG%2BWGBOvThCk3u8qd%2FvQs%2FnWDt8y7%2BrVyT8vx5rYrujV734CggZRK%2BG5EV1jpTQbMSGogTX19eAEbArd4Ca640aPeeGCPYYRHxmTJqJ7X%2BiN8oCWUVq4I%2FKy4nHYpJtlxZi%2FZhmOXzrrbdUTJ7h%2FjzPkUFd9L1s7kwf3xG0AZ2J2eNY%2F%2BwrR%2FzgICyzRIhOSyCcfDciyjZLUBLo27PyEdxfDzbNqU%2BB%2FrFVi9zMbqcSFe6pLkAKZtWMNKKACjJCSrky6Amx9nC2ZO4tG75oRZZ0Wkxc7dkyNspKxzYCBKRuSdO0pVBIfeTpH%2F6ZHIczPImcWHqzKVcsvRu4VRCwRA6nybBbg8ZPpUaZGrBqL%2FEaMhXDYyccNS9IlDbNUZczwizmER7azEhqtWDpSishH7H4IHnhFD%2FNTQEs4Oz%2Fz8YXLMz6QpcDg9dFmJcsmbuX4143txteaUpmBvZxkRwUY%2B9tHL4DMDvsDf1cV7nefr9loxD3Xv5qzXSTo%2F2sgpHUDEFF2GHuCqsRy3rAcHIA79GYdcarh%2BRkjTt1z20B5PgARhQ4jqZt2jaRD4pH9FyH%2BTuszg%3D%3D&ctl00%24plhMain%24tbxNumOfApplicants=1&ctl00%24plhMain%24cboVisaCategory=239&____Ticket=3&__VIEWSTATEENCRYPTED=&__EVENTVALIDATION=wdBz0rmhdMCS%2B1cdOfYuuMdDXD0mnMJEErXeezP6mrK%2BkFwVDrkzbGsXBfLbgE5E08O8BInTJ2u1vrR09YAtRnIxCZZj08%2FSmF5LS4Xm6mFeiYQa2T7v8kb%2FyIGm4zPxqdeNCEljsEndAIKYydGsSlTqH6WTAEUrfDl0e4KEx3VM3a8I5MMDtCIBqY%2BF%2BDC%2B";
		byte[] payload = postData.getBytes();
		request.setPayload(payload);
		HTTPResponse response;
		try{
			response = fetchService.fetch(request);
			String content = new String(response.getContent(), "utf-8");
			Pattern pattern = Pattern.compile(PATTERN);
			Matcher matcher = pattern.matcher(content);
			if(matcher.find()){	
				String message = matcher.group(1);
				logger.info("FetchAPI completed successfully: '" + message + "'");
				return message;				
			}
			else {
				logger.warning("Can't parse: " +  content);
			}			
		}
		catch(Exception ex){			
			logger.log(Level.SEVERE, ex.getMessage(), ex);
		}
		
		return null;
	}
}
